#include"bitmap.h"
#include"stdlib.h"
#include"stdio.h"

Bitmap::Bitmap(){}

void Bitmap::initialize(char* bitmap,const int length)
{
    this->bitmap = bitmap;
    this->length = length;
    int bytes = ceil(length,8);
    for(int i=0; i<bytes; i++)
    {
        bitmap[i] = 0;
    }
}
bool Bitmap::get(const int index) const
{
    int pos = index/8;
    int offset = index%8;
    return (bitmap[pos]&(1<<offset));
}
void Bitmap::set(const int index,const bool status)
{
    int pos=index/8;
    int offset=index%8;
    //清零
    bitmap[pos]=bitmap[pos]&(~(1<<offset));
    //置一
    if(status)
    {
        bitmap[pos]=bitmap[pos] | (1<<offset);
    }
}
int Bitmap::allocate(const int count)
{
    if(count==0)return -1;
    int index=0,empty,start;
    while(index<length)
    {
        //越过已经分配的资源
        while(index<length && get(index))index++;
        //不存在连续的count个资源
        if(index==length) return -1;
        //找到1个未分配的资源，检查是否为index开始的连续count个资源
        empty=0;
        start=index;
        while((index<length)&&(!get(index))&&(empty<count))
        {
            empty++;
            index++;
        }
        //存在连续个count个资源
        if(empty==count)
        {
            for(int i=0;i<count;i++)
            {
                set(start+i,true);
            }
            return start;
        }
    }
    return -1;
}
void Bitmap::release(const int index,const int count)
{
    for(int i=0; i<count; i++)
    {
        set(index+i,false);
    }
}
char* Bitmap::getBitmap()
{
    return (char*)bitmap;
}
int Bitmap::size() const
{
    return length;
}